/*
 * Copyright (C) 2011-2018 ShenZhen iBOXSaaS Information Technology Co.,Ltd.
 * 
 * All right reserved.
 * 
 * This software is the confidential and proprietary information of iBOXSaaS Company of China.
 * ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the contract agreement you entered into with iBOXSaaS inc.
 * 
 */

package com.iboxpay.open.gateway.utils;

import java.io.IOException;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.iboxpay.open.common.constants.ParamEnums;
import org.springframework.util.StreamUtils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * ParamUtils.java
 * 
 * @author xuxiao
 * @date 2018/07/02
 */
@Slf4j
public class ParamUtils {

    /**
     * 获取请求参数中包含的openId
     * @param request
     * @return
     */
    public static String getOpenId(HttpServletRequest request) {
        String openId = request.getParameter(ParamEnums.openId.getCode());
        if (StringUtils.isNotBlank(openId)) {
            return openId;
        }
        try {
            String requestBody = getRequestBody(request);
            JsonNode jsonNode;
            jsonNode = new ObjectMapper().readTree(requestBody);
            JsonNode openIdNode = jsonNode.get(ParamEnums.openId.getCode());
            if (openIdNode != null) {
                return openIdNode.asText();
            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取请求body
     * @param request
     * @return
     */
    public static String getRequestBody(HttpServletRequest request) {
        try {
            return StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
        } catch (IOException e) {
            log.info(e.getMessage(), e);
        }
        return null;
    }

}
